<template>
	<view>
		<canvas type="2d" canvas-id="xprogress" id="xprogress"
			:style="[`width:${props.width}px`, `height:${props.height}px`]"></canvas>
	</view>
</template>

<script lang="ts" setup>
import { defineProps,watch, getCurrentInstance } from "vue";
import { onReady } from "@dcloudio/uni-app";
const props = withDefaults(defineProps<{
	width?: number
	height?: number
	value?: number
	color?: string
	bgColor?: string
	progressColor?: string
	lineWidth?: number
}>(), {
	width: 100,
	height: 100,
	value: 0,
	bgColor: '#FFFFFF',
	progressColor: '#FF0000',
	color: '#FFFFFF',
	lineWidth: 26
});
watch(() => props.value, (v:number) => {
	animate(v);
})
let ctx: any, canvas: any, centerX: number, centerY: number, radius: number,  gradient: any;
onReady(() => {
	const query = uni.createSelectorQuery().in(getCurrentInstance());
	query.select('#xprogress')
		.fields({ node: true, size: true })
		.exec((res) => {
			canvas = res[0].node
			ctx = canvas.getContext('2d')
			console.log(ctx);
			canvas.width = props.width;
			canvas.height = props.height;
			centerX = props.width / 2;
			centerY = props.height / 2;
			radius = (props.width / 2) - props.lineWidth;
			console.log(centerX, centerY, radius);

			// 进度条的渐变颜色
			gradient = ctx.createLinearGradient(0, 0, props.width, 0);
			gradient.addColorStop(0, 'white');
			gradient.addColorStop(1, props.progressColor);
			drawProgress(props.value);
		});
})
const drawProgress = (progress: number) => {
	ctx.clearRect(0, 0, props.width, props.height);

	// 画背景圆环
	ctx.beginPath();
	ctx.arc(centerX, centerY, radius, Math.PI, Math.PI * 2);
	ctx.lineWidth = props.lineWidth;
	ctx.strokeStyle = props.bgColor
	ctx.lineCap = 'round'; // 让进度条的两端是圆形的
	ctx.stroke();
	if (progress > 0) {
		// 画进度条
		ctx.beginPath();
		ctx.arc(centerX, centerY, radius, Math.PI, Math.PI + Math.PI * progress / 100);
		ctx.strokeStyle = gradient;
		ctx.lineWidth = props.lineWidth - 8;
		ctx.lineCap = 'round'; // 让进度条的两端是圆形的
		ctx.stroke();
	}
	ctx.beginPath();
	ctx.textAlign = 'center';
	ctx.textBaseline = 'middle';
	ctx.font = `bold ${props.width / 5}px Arial`;
	ctx.fillStyle = props.color;
	const l = ctx.measureText(progress).width;
	ctx.fillText(progress, centerX, centerY * 0.8);
	ctx.font = `bold ${props.width / 10}px Arial`;
	ctx.fillText('%', centerX + l, centerY * 0.8);
	ctx.font = `bold ${props.width / 20}px Arial`;
	ctx.fillText('正确率', centerX, centerY * 1.2);
}
const animate = (progress: number) => {
	let p = 10;
	let timer = setInterval(() => {
		p++;
		drawProgress(p);
		if (p >= 100 || p >= progress) {
			clearInterval(timer);
		}
	}, 10);
}
</script>

<style></style>